<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getApiUrl, API_ENDPOINTS } from '../config/api'

interface Activity {
  id: number
  name: string
  date: string
  time: string
  location: string
  participants: number
  status: string
  description?: string
}

const activities = ref<Activity[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const formData = ref({
  name: '',
  date: '',
  time: '',
  location: '',
  participants: 0,
  status: '计划中',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  time: [{ required: true, message: '请选择时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  participants: [{ required: true, message: '请输入参与人数', trigger: 'blur' }]
}

// Fetch activities
const fetchActivities = async () => {
  try {
    loading.value = true
    const response = await fetch(getApiUrl(API_ENDPOINTS.activities))
    if (!response.ok) throw new Error('获取数据失败')
    const data = await response.json()
    activities.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('获取活动列表失败')
    activities.value = []
  } finally {
    loading.value = false
  }
}

// Add new activity
const addActivity = async () => {
  try {
    const response = await fetch(getApiUrl(API_ENDPOINTS.activities), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('添加失败')
    
    ElMessage.success('添加活动成功')
    dialogVisible.value = false
    await fetchActivities()
    resetForm()
  } catch (error) {
    ElMessage.error('添加活动失败')
  }
}

// Edit activity
const editActivity = async () => {
  if (!currentId.value) return
  
  try {
    const response = await fetch(getApiUrl(`${API_ENDPOINTS.activities}/${currentId.value}`), {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('更新失败')
    
    ElMessage.success('更新活动成功')
    dialogVisible.value = false
    await fetchActivities()
    resetForm()
  } catch (error) {
    ElMessage.error('更新活动失败')
  }
}

// Delete activity
const deleteActivity = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该活动吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await fetch(getApiUrl(`${API_ENDPOINTS.activities}/${id}`), {
      method: 'DELETE'
    })

    if (!response.ok) throw new Error('删除失败')
    
    ElMessage.success('删除活动成功')
    await fetchActivities()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除活动失败')
    }
  }
}

// Handle edit button click
const handleEdit = (row: Activity) => {
  isEdit.value = true
  currentId.value = row.id
  formData.value = { ...row }
  dialogVisible.value = true
}

// Handle add button click
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleSubmit = () => {
  if (isEdit.value) {
    editActivity()
  } else {
    addActivity()
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    date: '',
    time: '',
    location: '',
    participants: 0,
    status: '计划中',
    description: ''
  }
}

onMounted(() => {
  fetchActivities()
})
</script>

<template>
  <div class="activities">
    <div class="header">
      <h2>活动安排</h2>
      <el-button type="primary" @click="handleAdd">添加活动</el-button>
    </div>

    <el-table 
      :data="activities" 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="活动名称" />
      <el-table-column prop="date" label="日期" />
      <el-table-column prop="time" label="时间" />
      <el-table-column prop="location" label="地点" />
      <el-table-column prop="participants" label="参与人数" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '进行中' ? 'success' : row.status === '已取消' ? 'danger' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            link 
            type="primary" 
            @click="handleEdit(row)"
            :disabled="row.status === '已取消'"
          >
            编辑
          </el-button>
          <el-button 
            link 
            type="danger" 
            @click="deleteActivity(row.id)"
            :disabled="row.status === '已取消'"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Activity Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑活动' : '添加活动'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="formData.date"
            type="date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-time-picker
            v-model="formData.time"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="���点" prop="location">
          <el-input v-model="formData.location" />
        </el-form-item>
        <el-form-item label="参与人数" prop="participants">
          <el-input-number 
            v-model="formData.participants" 
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="计划中" value="计划中" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.activities {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>